/**
 * 描述: 给角色分配权限，子页面
 * 日期：2019-07-24
 */

(function(KIT, RES) {
  var URL_ROOT = RES.URL_ROOT + "/role",
    URL_SAVE = URL_ROOT + "/saveRolePermissions",
    URL_GET_MENU_TREE = URL_ROOT + "/getMenusTree",
    URL_FIND_CHECKED_MENUS = URL_ROOT + "/checkMenus";

  var _menuTree = function(options) {
    if(arguments.length === 1) {
      return $("#menuTree").g_jstree(rapid.nvl(options, {}));
    }
    return $("#menuTree").g_jstree();
  };

  rapid.Page.create({
    methods: {
      _initBtn_: function() {
        var __page = this;

        rapid.ui("#btnSaveRolePermission").on("click", function() {
          rapid.confirm("确定要保存吗？", function(e) {
            if(e) {
              __page._saveRolePermissions_();
            }
          });
        });

        rapid.ui("#btnCloseRolePermission").on("click", function() {
          __page.hide();
        });

        return this;
      },

      _initTree_: function() {
        var roleId = rapid("#permissionForm").findByName("roleId").val();

        _menuTree({
          checkbox: true,
          data: {
            url: URL_GET_MENU_TREE
          },
          onloaded: function() {
            rapid.get({
              url: URL_FIND_CHECKED_MENUS,
              data: "roleId=" + roleId,
              success: function(data) {
                _menuTree().checknodes(data);
              }
            })
          }
        });

        return this;
      },

      _saveRolePermissions_: function() {
        var roleId = rapid("#permissionForm").findByName("roleId").val();
        var menuIds = _menuTree().getchecked().toString();
        var __page = this;
        rapid.post({
          url: URL_SAVE,
          data: {
            roleId: roleId,
            menuIds: menuIds
          },
          success: function() {
            window.parent.rapid.success();
            __page.hide();
          }
        });
        return this;
      }
    }
  })(function() {
    this._initBtn_();
    this._initTree_();

  }).init();
})(rapid.kit, rapid.res);